<?php
/**
 * Created by PhpStorm.
 * User: lhl
 * Date: 2020/10/12
 * Time: 14:24
 * Features: api模块service的Trait
 */

namespace app\common\traits;

use app\common\exception\CustomException;

use app\common\service\ServerVersion;
use think\Db;
use think\exception\ValidateException;
use think\facade\Request;

Trait ApiServiceTrait
{
    //引入公共Trait
    use CommonServiceTrait;

    /**
     * api模块的json输出
     * @param array $data 数据
     */
    public function jsonOutPut ($data = [], $is_call = false)
    {
        global $errCode;
        global $errMsg;

        $authServer = new ServerVersion();
        $version = $authServer->getServerVersion();

        $outData = [
            'code' => $errCode,
            'message' => $errMsg,
            'version' => $version,
            'request_date' => date('Y-m-d H:i:s'),
        ];

        isset($data['data']) ? $outData = array_merge($outData, $data) : $outData['data'] = $data;

        return json($outData);
    }

    /**
     * 修改通信日志回调状态
     * @param bool $isMust logId参数是否为必须
     *
     * @return int
    */
    public function setCallBackStatus($isMust = true){
        global $logId;
        $logId = $logId ? $logId : Request::param('logId');
        if(!$logId && $isMust){
            throw new ValidateException('数据错误 缺少必须参数logId',201);
        }
        if($logId){
            return Db::name('server_socket_message_history')->where('id',$logId)->setField('callback_status',1);
        }else{
            return 0;
        }
    }

    /**
     * 根据host_key查询host_id
     * @param string $hostKey 主机绑定码
    */
    public function getHostIdByHostKey($hostKey){
        if(!$hostKey){
            throw new CustomException('缺少必要参数hostkey');
        }
        $hostId = Db::name('host')->where('hostkey',$hostKey)->value('id');
        if(!$hostId){
            throw new CustomException('该hostkey对应的主机不存在');
        }
        return $hostId;
    }

}